<template>
  <a-layout>
    <a-layout-content style="padding: 24px;" >
      <div>
        <a-row class="headRow">
          <a-col :span="12">
            <a-select v-model:value="status" style="width: 200px;">
              <a-select-option value="received">我收到的授权</a-select-option>
              <a-select-option value="sent">我发起的授权</a-select-option>
            </a-select>
          </a-col>
        </a-row>
      </div>
      <!-- 表格内容 -->
      <template v-if="status === 'received'">
        <a-table :columns="receivedColumns" :data-source="receivedData" :pagination="false" :scroll="{y:'65vh'}">
          <template #bodyCell="{column, record}">
            <template v-if="column.key === 'status'">
              <span>
                <a-tag v-if="record.status === 1" color="processing">等待授权</a-tag>
                <a-tag v-else-if="record.status === 2" color="success">已同意</a-tag>
                <a-tag v-else-if="record.status === 3" color="error">已拒绝</a-tag>
                <a-tag v-else-if="record.status === 4" color="default">已撤销</a-tag>
              </span>
            </template>
            <template v-if="column.key === 'action'">
              <span>
                <!-- 等待授权状态显示同意/拒绝按钮 -->
                <template v-if="record.status === 1">
                  <a :class="{ disabled: isOperating }" @click="!isOperating && handleApproveDetail(record)">同意</a>
                  <a-divider type="vertical" />
                  <a :class="{ disabled: isOperating }" @click="!isOperating && handleDenyDetail(record)">拒绝</a>
                </template>
                <!-- 已同意状态显示撤销按钮 -->
                <template v-if="record.status === 2">
                  <a :class="{ disabled: isOperating }" @click="!isOperating && handleRevokeAccess(record)">撤销授权</a>
                </template>
              </span>
            </template>
          </template>
        </a-table>
      </template>
      <template v-if="status === 'sent'">
        <a-table :columns="sentColumns" :data-source="sentData" :pagination="false" :scroll="{y:'65vh'}">
          <template #bodyCell="{column, record}">
            <template v-if="column.key === 'status' ">
              <span>
                <a-tag v-if="record.status === 1" color="processing">等待授权</a-tag>
                <a-tag v-else-if="record.status === 2" color="success">已同意</a-tag>
                <a-tag v-else-if="record.status === 3" color="error">已拒绝</a-tag>
                <a-tag v-else-if="record.status === 4" color="default">已撤销</a-tag>
              </span>
            </template>
            <template v-if="column.key === 'transfer_status'">
              <span>
                <a-tag v-if="record.transfer_status === 0" color="default">未转移</a-tag>
                <a-tag v-else-if="record.transfer_status === 1" color="success">已转移</a-tag>
              </span>
            </template>
            <template v-if="column.key === 'action'">
              <span>
                <a v-if="record.status === 2" :class="{ disabled: isOperating }" @click="!isOperating && handleViewData(record)">查看数据</a>
                <a-divider v-if="record.status === 2 && record.transfer_status === 0" type="vertical" />
                <a v-if="record.status === 2 && record.transfer_status === 0" :class="{ disabled: isOperating }" @click="!isOperating && handleTransferData(record)">转移数据</a>
              </span>
            </template>
          </template>
        </a-table>
      </template>
    </a-layout-content>

    <!-- 转移数据的对话框 -->

    <!-- 转移数据的对话框 -->
    <a-modal
        title="转移数据"
        :visible="transferModalVisible"
        :confirmLoading="isOperating"
        @ok="handleTransferConfirm"
        @cancel="closeTransferModal"
    >
      <a-form :model="transferForm">
        <a-form-item label="目标表名">
          <a-input v-model:value="transferForm.targetTable" placeholder="请输入目标表名" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-layout>
</template>

<script>
import { defineComponent } from 'vue';
import { message, Tag } from 'ant-design-vue';
import axiosInstance from '@/axios/axios.js';

export default defineComponent({
  components: {
    [Tag.name]: Tag
  },
  data() {
    return {
      isOperating: false,
      status: "received",
      dataDrawerVisible: false,
      transferModalVisible: false,
      transferForm: {
        targetTable: '',
      },
      currentRecord: null,
      authorizedData: null,
      // 实验集表格列定义
      experimentSetColumns: [
        {
          title: "实验集名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "描述",
          dataIndex: "description",
          key: "description",
        },
        {
          title: "创建者",
          dataIndex: "creator",
          key: "creator",
        },
        {
          title: "领域",
          dataIndex: "field",
          key: "field",
        },
      ],
      // 批次表格列定义
      batchColumns: [
        {
          title: "批次名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "描述",
          dataIndex: "description",
          key: "description",
        },
      ],
      // 实验表格列定义
      experimentColumns: [
        {
          title: "实验名称",
          dataIndex: "experiment_name",
          key: "experiment_name",
        },
        {
          title: "描述",
          dataIndex: "description",
          key: "description",
        },
        {
          title: "创建者",
          dataIndex: "creator",
          key: "creator",
        },
      ],
      // 图片表格列定义
      imageColumns: [
        {
          title: "图片名称",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "文件大小",
          dataIndex: "file_size",
          key: "file_size",
        },
        {
          title: "类型",
          dataIndex: "mime_type",
          key: "mime_type",
        },
        {
          title: "创建时间",
          dataIndex: "created_at",
          key: "created_at",
        },
      ],
      receivedColumns: [
        {
          title: "实验集名称",
          dataIndex: "experiment_set_name",
          key: "experiment_set_name",
        },
        {
          title: "请求用户",
          dataIndex: "sender_name",
          key: "sender_name",
        },
        {
          title: "请求发起时间",
          dataIndex: "create_time",
          key: "create_time",
        },
        {
          title: "状态",
          key: "status",
        },
        {
          title: "操作",
          key: "action",
          scopedSlots: {customRender: "action"},
        },
      ],
      sentColumns: [
        {
          title: "实验集名称",
          dataIndex: "experiment_set_name",
          key: "experiment_set_name",
        },
        {
          title: "被请求用户",
          dataIndex: "receiver_name",
          key: "receiver_name",
        },
        {
          title: "请求发起时间",
          dataIndex: "create_time",
          key: "create_time",
        },
        {
          title: "过期时间",
          dataIndex: "expire_time",
          key: "expire_time",
        },
        {
          title: "状态",
          key: "status",
        },
        {
          title: "转移状态",
          key: "transfer_status",
        },
        {
          title: "操作",
          key: "action",
        },
      ],
      receivedData: [],
      sentData: [],
    };
  },
  computed: {
    hasAnyData() {
      if (!this.authorizedData) return false;
      return (
        (this.authorizedData.experimentSets && this.authorizedData.experimentSets.length > 0) ||
        (this.authorizedData.batches && this.authorizedData.batches.length > 0) ||
        (this.authorizedData.experiments && this.authorizedData.experiments.length > 0) ||
        (this.authorizedData.images && this.authorizedData.images.length > 0)
      );
    }
  },
  watch: {
    status() {
      this.loadData();
    }
  },
  async created() {
    await this.loadData();
  },
  methods: {
    async loadData() {
      try {
        const userAddress = this.$cookies.get("userAddress");
        if (!userAddress) {
          message.error('用户信息不完整，请重新登录');
          this.$router.push('/login');
          return;
        }

        // 加载收到的授权请求
        if (this.status === 'received') {
          const receivedResponse = await axiosInstance({
            method: "POST",
            url: "/grant/getGrantRequestsByReceiverAddress",
            data: {
              userAddress,
            }
          });

          console.log('Received response:', receivedResponse.data);

          if (receivedResponse.data?.data?.grantRequests) {
            // 显示所有状态的请求
            this.receivedData = receivedResponse.data.data.grantRequests;
            console.log('Received grant requests:', this.receivedData);
          }
        }

        // 加载发出的授权请求
        if (this.status === 'sent') {
          const sentResponse = await axiosInstance({
            method: "POST",
            url: "/grant/getGrantRequestsBySenderAddress",
            data: {
              userAddress,
            }
          });

          console.log('Sent response:', sentResponse.data);

          if (sentResponse.data?.data?.grantRequests) {
            this.sentData = sentResponse.data.data.grantRequests;
          }
        }

      } catch (error) {
        console.error('获取授权数据失败:', error);
        message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
      }
    },
    async handleApproveDetail(record) {
      if (this.isOperating) return;

      this.isOperating = true;
      message.loading('正在处理授权请求...', 0);

      try {
        console.log('Approving grant request:', record);

        const requestData = {
          grantRequestId: record.grant_request_id,
          grantorAddress: this.$cookies.get("userAddress"),
          grantorName: this.$cookies.get("username"),
          granteeAddress: record.sender_address,
          granteeName: record.sender_name,
          experimentSetId: record.experiment_set_id,
          batchIds: [], // 如果需要限制批次，可以在这里添加
        };

        console.log('Request data:', requestData);

        await axiosInstance({
          method: "POST",
          url: "/grant/approveGrantRequest",
          data: requestData,
        });

        message.success('已同意授权请求');
        await this.loadData(); // 重新加载数据
      } catch (error) {
        console.error('处理授权请求失败:', error);
        message.error(`处理失败: ${error.response?.data?.message || error.message}`);
      } finally {
        message.destroy();
        this.isOperating = false;
      }
    },
    async handleDenyDetail(record) {
      if (this.isOperating) return;

      this.isOperating = true;
      message.loading('正在处理授权请求...', 0);

      try {
        await axiosInstance({
          method: "POST",
          url: "/grant/denyGrantRequest",
          data: {
            grantRequestId: record.grant_request_id,
          },
        });

        message.success('已拒绝授权请求');
        await this.loadData(); // 重新加载数据
      } catch (error) {
        console.error('处理授权请求失败:', error);
        message.error(`处理失败: ${error.response?.data?.message || error.message}`);
      } finally {
        message.destroy();
        this.isOperating = false;
      }
    },
    async handleRevokeAccess(record) {
      if (this.isOperating) return;

      this.isOperating = true;
      message.loading('正在撤销授权...', 0);

      try {
        const requestData = {
          grantRequestId: record.grant_request_id,
          grantorAddress: this.$cookies.get("userAddress"),
        };

        await axiosInstance({
          method: "POST",
          url: "/grant/revokeAccess",
          data: requestData,
        });

        message.success('已撤销授权');
        await this.loadData(); // 重新加载数据
      } catch (error) {
        console.error('撤销授权失败:', error);
        message.error(`撤销失败: ${error.response?.data?.message || error.message}`);
      } finally {
        message.destroy();
        this.isOperating = false;
      }
    },
    async handleViewData(record) {
      if (this.isOperating) return;

      this.isOperating = true;
      message.loading('正在加载数据...', 0);

      try {
        console.log('Viewing data for record:', record);
        
        const response = await axiosInstance({
          method: "GET",
          url: `/data-access/authorized-data/${record.grant_request_id}`
        });

        console.log('View data response:', response.data);

        if (response.data?.code === 200 && Array.isArray(response.data?.data)) {
          const responseData = response.data.data;
          console.log('Response data:', responseData);
          console.log('Current record:', record);
          console.log('Record fields:', {
            experiment_set_id: record.experiment_set_id,
            experiment_set_name: record.experiment_set_name,
            grant_request_id: record.grant_request_id,
            id: record.id
          });
          console.log('Current record:', record);
          console.log('Grant request ID:', record.grant_request_id || record.id);
          
          // 根据后端返回的table_type字段分类数据
          const experimentSets = responseData.filter(item => item.table_type === 'experiment_set');
          const batches = responseData.filter(item => item.table_type === 'batch');
          const experiments = responseData.filter(item => item.table_type === 'experiment');
          const images = responseData.filter(item => item.table_type === 'image');
          const files = responseData.filter(item => item.table_type === 'file');

          console.log('Data classification by table_type:', {
            experimentSets: experimentSets.length,
            batches: batches.length,
            experiments: experiments.length,
            images: images.length,
            files: files.length
          });

          // 根据reference_type进一步分类文件
          const experimentSetFiles = files.filter(f => f.reference_type === 'experiment_set');
          const batchFiles = files.filter(f => f.reference_type === 'batch');
          const experimentFiles = files.filter(f => f.reference_type === 'experiment');

          console.log('Images data:', images);

          console.log('Classified data:', {
            experimentSets,
            batches,
            experiments,
            images,
            experimentSetFiles,
            batchFiles,
            experimentFiles
          });

          if (batches.length > 0) {
            // 导航到批次页面
            this.$router.push({
              path: '/Grant/AuthorizedBatch',
              query: {
                experimentSetName: record.experiment_set_name,
                experimentSetId: record.experiment_set_id,
                batchData: JSON.stringify(batches),
                allData: JSON.stringify({
                  experimentSets,
                  batches,
                  experiments,
                  images,
                  experimentSetFiles,
                  batchFiles,
                  experimentFiles
                }),
                accessId: record.grant_request_id || record.id // 添加accessId参数，兼容两种字段名
              }
            });
          } else {
            message.warning('没有找到批次数据');
          }
        } else {
          message.warning('暂无数据');
        }
      } catch (error) {
        console.error('获取授权数据失败:', error);
        if (error.response?.status === 403) {
          message.error('无权访问此数据');
        } else {
          message.error(`获取数据失败: ${error.response?.data?.message || error.message}`);
        }
      } finally {
        message.destroy();
        this.isOperating = false;
      }
    },
    handleTransferData(record) {
      this.currentRecord = record;
      this.transferForm.targetTable = `transferred_${record.experiment_set_id}`;
      this.transferModalVisible = true;
    },
    async handleTransferConfirm() {
      if (!this.currentRecord || !this.transferForm.targetTable) return;

      this.isOperating = true;
      message.loading('正在转移数据...', 0);

      try {
        await axiosInstance({
          method: "POST",
          url: `/data-access/transfer/${this.currentRecord.grant_request_id}`,
          params: {
            targetTable: this.transferForm.targetTable,
            granteeAddress: this.$cookies.get("userAddress"),
          },
        });

        message.success('数据转移成功');
        this.closeTransferModal();
        await this.loadData(); // 重新加载数据
      } catch (error) {
        console.error('数据转移失败:', error);
        message.error(`转移失败: ${error.response?.data?.message || error.message}`);
      } finally {
        message.destroy();
        this.isOperating = false;
      }
    },
    closeDataDrawer() {
      this.dataDrawerVisible = false;
      this.authorizedData = null;
    },
    closeTransferModal() {
      this.transferModalVisible = false;
      this.currentRecord = null;
      this.transferForm.targetTable = '';
    },
  }
});
</script>

<style scoped>
.disabled {
  pointer-events: none;
  opacity: 0.5;
}
.headRow {
  margin-bottom: 20px;
}
</style>